package com.example.demo.admin.core.shiro.factory;/**
 * Created by kete on 2017-10-20.
 */

import com.example.demo.common.persistence.dao.MenuDao;
import com.example.demo.common.persistence.dao.RoleMapper;
import com.example.demo.common.persistence.dao.UserMgrDao;
import com.example.demo.common.persistence.model.Role;
import com.example.demo.common.persistence.model.User;
import com.example.demo.common.vo.ShiroUser;
import com.example.demo.core.util.ConvertUtil;
import com.example.demo.core.util.SpringContextHolder;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：kete
 * 创建时间：2017-10-20 17:08
 * 功能描述：
 * 版本：
 */
@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class ShiroFactory implements Ishiro {

    @Autowired
    UserMgrDao userMgrDao;

    @Autowired
    MenuDao menuDao;

    @Autowired
    RoleMapper roleMapper;

    public static Ishiro me() {
        return SpringContextHolder.getBean(Ishiro.class);
    }

    @Override
    public User user(String account) {

        return userMgrDao.getByAccount(account);
    }

    @Override
    public ShiroUser shiroUser(User user) {
        ShiroUser shiroUser = new ShiroUser();
        BeanUtils.copyProperties(user,shiroUser);

        Integer[] roleIdArray = ConvertUtil.toIntArray(user.getRoleid());

        List<Integer> roleList = new ArrayList<Integer>();
        List<String> roleNameList = new ArrayList<String>();

        for(Integer roleId : roleIdArray){
            roleList.add(roleId);
            roleNameList.add(this.findRoleNameByRoleId(roleId));

        }

        shiroUser.setRoleList(roleList);
        shiroUser.setRoleNames(roleNameList);

        return shiroUser;
    }

    @Override
    public List<String> findPermissionsByRoleId(Integer roleId) {
        List<String> resUrls = menuDao.getResUrlsByRoleId(roleId);
        return resUrls;
    }

    @Override
    public String findRoleNameByRoleId(Integer roleId) {

        Role role = roleMapper.selectById(roleId);
        String roleName = role !=null ? role.getName() : "";

        return roleName;
    }

    @Override
    public SimpleAuthenticationInfo info(ShiroUser shiroUser, User user, String realmName) {

        String credentials = user.getPassword();
        // 密码加盐处理
        String source = user.getSalt();
        ByteSource credentialsSalt = new Md5Hash(source);

        return new SimpleAuthenticationInfo(shiroUser,credentials,credentialsSalt,realmName);
    }
}
